<template>
  <el-dialog
    :title="dialogTitle"
    :visible.sync="visible"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    class="inventory-detail-dialog"
    @close="handleClose"
  >
    <div class="inventory-detail-content" v-loading="loading">
      <!-- 设备基本信息 -->
      <div class="device-info-section">
        <h3 class="section-title">
          <i class="el-icon-mobile-phone"></i>
          设备信息
        </h3>
        <div class="device-info-card">
          <div class="device-info-row">
            <span class="info-label">设备名称:</span>
            <span class="info-value">{{ deviceInfo.deviceName || '-' }}</span>
          </div>
          <div class="device-info-row">
            <span class="info-label">设备编码:</span>
            <span class="info-value">{{ deviceInfo.deviceCode || '-' }}</span>
          </div>
          <div class="device-info-row">
            <span class="info-label">品牌型号:</span>
            <span class="info-value">{{ deviceInfo.brand || '-' }} {{ deviceInfo.model || '' }}</span>
          </div>
        </div>
      </div>

      <!-- 库存详情表单 -->
      <div class="inventory-form-section">
        <h3 class="section-title">
          <i class="el-icon-goods"></i>
          库存详情
          <el-tag v-if="!hasInventory" type="info" size="mini">暂无库存记录</el-tag>
        </h3>
        
        <el-form 
          ref="inventoryForm" 
          :model="inventoryForm" 
          :rules="inventoryRules" 
          label-width="120px"
          class="inventory-form"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="总数量" prop="totalQuantity">
                <el-input-number 
                  v-model="inventoryForm.totalQuantity" 
                  :min="0" 
                  :max="9999"
                  placeholder="请输入总数量"
                  style="width: 100%"
                  @change="handleTotalQuantityChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="可用数量" prop="availableQuantity">
                <el-input-number 
                  v-model="inventoryForm.availableQuantity" 
                  :min="0" 
                  :max="inventoryForm.totalQuantity || 9999"
                  placeholder="请输入可用数量"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="已租出数量" prop="rentedQuantity">
                <el-input-number 
                  v-model="inventoryForm.rentedQuantity" 
                  :min="0" 
                  :max="inventoryForm.totalQuantity || 9999"
                  placeholder="请输入已租出数量"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="维修中数量" prop="maintenanceQuantity">
                <el-input-number 
                  v-model="inventoryForm.maintenanceQuantity" 
                  :min="0" 
                  :max="inventoryForm.totalQuantity || 9999"
                  placeholder="请输入维修中数量"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="损坏数量" prop="damagedQuantity">
                <el-input-number 
                  v-model="inventoryForm.damagedQuantity" 
                  :min="0" 
                  :max="inventoryForm.totalQuantity || 9999"
                  placeholder="请输入损坏数量"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数量检查">
                <div class="quantity-check">
                  <span :class="{'text-success': isQuantityValid, 'text-danger': !isQuantityValid}">
                    合计: {{ calculatedTotal }} / 总数: {{ inventoryForm.totalQuantity || 0 }}
                  </span>
                  <el-tag v-if="!isQuantityValid" type="warning" size="mini">
                    数量不匹配
                  </el-tag>
                  <el-tag v-else type="success" size="mini">
                    数量正确
                  </el-tag>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 库存状态统计 -->
      <div class="inventory-stats-section" v-if="hasInventory">
        <h3 class="section-title">
          <i class="el-icon-pie-chart"></i>
          库存状态统计
        </h3>
        <div class="stats-grid">
          <div class="stat-item available">
            <div class="stat-icon">
              <i class="el-icon-check"></i>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ inventoryForm.availableQuantity || 0 }}</div>
              <div class="stat-label">可用</div>
            </div>
          </div>
          <div class="stat-item rented">
            <div class="stat-icon">
              <i class="el-icon-time"></i>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ inventoryForm.rentedQuantity || 0 }}</div>
              <div class="stat-label">已租出</div>
            </div>
          </div>
          <div class="stat-item maintenance">
            <div class="stat-icon">
              <i class="el-icon-setting"></i>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ inventoryForm.maintenanceQuantity || 0 }}</div>
              <div class="stat-label">维修中</div>
            </div>
          </div>
          <div class="stat-item damaged">
            <div class="stat-icon">
              <i class="el-icon-warning"></i>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ inventoryForm.damagedQuantity || 0 }}</div>
              <div class="stat-label">损坏</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose" size="medium">取 消</el-button>
      <el-button type="primary" @click="handleSave" size="medium" :loading="saving">
        {{ hasInventory ? '更新库存' : '创建库存' }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getInventory, addInventory, updateInventory } from "@/api/system/inventory";

export default {
  name: "InventoryDetailDialog",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    deviceInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      loading: false,
      saving: false,
      hasInventory: false,
      inventoryForm: {
        inventoryId: null,
        deviceId: null,
        totalQuantity: 0,
        availableQuantity: 0,
        rentedQuantity: 0,
        maintenanceQuantity: 0,
        damagedQuantity: 0
      },
      inventoryRules: {
        totalQuantity: [
          { required: true, message: "总数量不能为空", trigger: "blur" },
          { type: 'number', min: 0, message: "总数量不能小于0", trigger: "blur" }
        ],
        availableQuantity: [
          { required: true, message: "可用数量不能为空", trigger: "blur" },
          { type: 'number', min: 0, message: "可用数量不能小于0", trigger: "blur" }
        ],
        rentedQuantity: [
          { type: 'number', min: 0, message: "已租出数量不能小于0", trigger: "blur" }
        ],
        maintenanceQuantity: [
          { type: 'number', min: 0, message: "维修中数量不能小于0", trigger: "blur" }
        ],
        damagedQuantity: [
          { type: 'number', min: 0, message: "损坏数量不能小于0", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    dialogTitle() {
      return `${this.deviceInfo.deviceName || '设备'} - 库存详情`;
    },
    calculatedTotal() {
      const available = this.inventoryForm.availableQuantity || 0;
      const rented = this.inventoryForm.rentedQuantity || 0;
      const maintenance = this.inventoryForm.maintenanceQuantity || 0;
      const damaged = this.inventoryForm.damagedQuantity || 0;
      return available + rented + maintenance + damaged;
    },
    isQuantityValid() {
      return this.calculatedTotal === (this.inventoryForm.totalQuantity || 0);
    }
  },
  watch: {
    visible(newVal) {
      if (newVal && this.deviceInfo.deviceId) {
        this.loadInventoryData();
      }
    }
  },
  methods: {
    /** 加载库存数据 */
    async loadInventoryData() {
      if (!this.deviceInfo.deviceId) return;
      
      this.loading = true;
      try {
        // 如果设备已有库存信息，直接使用
        if (this.deviceInfo.inventory) {
          this.hasInventory = true;
          this.inventoryForm = {
            inventoryId: this.deviceInfo.inventory.inventoryId,
            deviceId: this.deviceInfo.deviceId,
            totalQuantity: this.deviceInfo.inventory.totalQuantity || 0,
            availableQuantity: this.deviceInfo.inventory.availableQuantity || 0,
            rentedQuantity: this.deviceInfo.inventory.rentedQuantity || 0,
            maintenanceQuantity: this.deviceInfo.inventory.maintenanceQuantity || 0,
            damagedQuantity: this.deviceInfo.inventory.damagedQuantity || 0
          };
        } else {
          // 尝试通过设备ID查询库存信息
          try {
            const response = await getInventory(this.deviceInfo.deviceId);
            if (response.data) {
              this.hasInventory = true;
              this.inventoryForm = {
                inventoryId: response.data.inventoryId,
                deviceId: this.deviceInfo.deviceId,
                totalQuantity: response.data.totalQuantity || 0,
                availableQuantity: response.data.availableQuantity || 0,
                rentedQuantity: response.data.rentedQuantity || 0,
                maintenanceQuantity: response.data.maintenanceQuantity || 0,
                damagedQuantity: response.data.damagedQuantity || 0
              };
            } else {
              this.initEmptyInventory();
            }
          } catch (error) {
            // 如果查询失败，说明没有库存记录，初始化空库存
            this.initEmptyInventory();
          }
        }
      } catch (error) {
        console.error('加载库存数据失败:', error);
        this.initEmptyInventory();
      } finally {
        this.loading = false;
      }
    },

    /** 初始化空库存 */
    initEmptyInventory() {
      this.hasInventory = false;
      this.inventoryForm = {
        inventoryId: null,
        deviceId: this.deviceInfo.deviceId,
        totalQuantity: 0,
        availableQuantity: 0,
        rentedQuantity: 0,
        maintenanceQuantity: 0,
        damagedQuantity: 0
      };
    },

    /** 总数量变化处理 */
    handleTotalQuantityChange(value) {
      if (value < this.calculatedTotal) {
        // 如果新的总数量小于当前各项数量之和，优先保留可用数量
        const diff = this.calculatedTotal - value;
        if (this.inventoryForm.availableQuantity >= diff) {
          this.inventoryForm.availableQuantity -= diff;
        } else {
          // 如果可用数量不够减，则依次减少其他数量
          let remaining = diff - this.inventoryForm.availableQuantity;
          this.inventoryForm.availableQuantity = 0;
          
          if (remaining > 0 && this.inventoryForm.rentedQuantity >= remaining) {
            this.inventoryForm.rentedQuantity -= remaining;
          } else if (remaining > 0) {
            remaining -= this.inventoryForm.rentedQuantity;
            this.inventoryForm.rentedQuantity = 0;
            
            if (remaining > 0 && this.inventoryForm.maintenanceQuantity >= remaining) {
              this.inventoryForm.maintenanceQuantity -= remaining;
            } else if (remaining > 0) {
              remaining -= this.inventoryForm.maintenanceQuantity;
              this.inventoryForm.maintenanceQuantity = 0;
              
              if (remaining > 0) {
                this.inventoryForm.damagedQuantity = Math.max(0, this.inventoryForm.damagedQuantity - remaining);
              }
            }
          }
        }
      }
    },

    /** 保存库存数据 */
    async handleSave() {
      try {
        await this.$refs.inventoryForm.validate();
        
        if (!this.isQuantityValid) {
          this.$modal.msgError('库存数量不匹配，请检查后再提交！');
          return;
        }

        this.saving = true;
        
        const inventoryData = {
          deviceId: this.inventoryForm.deviceId,
          totalQuantity: this.inventoryForm.totalQuantity,
          availableQuantity: this.inventoryForm.availableQuantity,
          rentedQuantity: this.inventoryForm.rentedQuantity,
          maintenanceQuantity: this.inventoryForm.maintenanceQuantity,
          damagedQuantity: this.inventoryForm.damagedQuantity
        };

        if (this.hasInventory && this.inventoryForm.inventoryId) {
          // 更新现有库存
          inventoryData.inventoryId = this.inventoryForm.inventoryId;
          await updateInventory(inventoryData);
          this.$modal.msgSuccess('库存信息更新成功');
        } else {
          // 新增库存记录
          await addInventory(inventoryData);
          this.$modal.msgSuccess('库存信息创建成功');
          this.hasInventory = true;
        }

        this.$emit('refresh');
        this.handleClose();
      } catch (error) {
        console.error('保存库存数据失败:', error);
        this.$modal.msgError('保存失败，请重试！');
      } finally {
        this.saving = false;
      }
    },

    /** 关闭弹窗 */
    handleClose() {
      this.$emit('update:visible', false);
      this.$emit('close');
    }
  }
};
</script>

<style lang="scss" scoped>
.inventory-detail-dialog {
  .inventory-detail-content {
    max-height: 70vh;
    overflow-y: auto;
  }

  .section-title {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 16px;
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    border-bottom: 2px solid #f0f0f0;
    padding-bottom: 8px;

    i {
      color: #409eff;
    }
  }

  .device-info-section {
    margin-bottom: 24px;

    .device-info-card {
      background: #f8f9fa;
      border-radius: 8px;
      padding: 16px;
      border: 1px solid #e9ecef;

      .device-info-row {
        display: flex;
        align-items: center;
        margin-bottom: 8px;

        &:last-child {
          margin-bottom: 0;
        }

        .info-label {
          font-weight: 500;
          color: #666;
          min-width: 80px;
        }

        .info-value {
          color: #333;
          font-weight: 500;
        }
      }
    }
  }

  .inventory-form-section {
    margin-bottom: 24px;

    .inventory-form {
      .quantity-check {
        display: flex;
        align-items: center;
        gap: 8px;

        .text-success {
          color: #67c23a;
          font-weight: 500;
        }

        .text-danger {
          color: #f56c6c;
          font-weight: 500;
        }
      }

      .el-input-number {
        width: 100%;
      }
    }
  }

  .inventory-stats-section {
    .stats-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
      gap: 16px;

      .stat-item {
        display: flex;
        align-items: center;
        padding: 16px;
        border-radius: 8px;
        border: 1px solid #e9ecef;

        .stat-icon {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 12px;

          i {
            font-size: 18px;
            color: white;
          }
        }

        .stat-content {
          .stat-value {
            font-size: 20px;
            font-weight: 600;
            line-height: 1;
            margin-bottom: 4px;
          }

          .stat-label {
            font-size: 12px;
            color: #666;
          }
        }

        &.available {
          background: #f0f9ff;
          border-color: #67c23a;

          .stat-icon {
            background: #67c23a;
          }

          .stat-value {
            color: #67c23a;
          }
        }

        &.rented {
          background: #fff7ed;
          border-color: #e6a23c;

          .stat-icon {
            background: #e6a23c;
          }

          .stat-value {
            color: #e6a23c;
          }
        }

        &.maintenance {
          background: #f3e8ff;
          border-color: #722ed1;

          .stat-icon {
            background: #722ed1;
          }

          .stat-value {
            color: #722ed1;
          }
        }

        &.damaged {
          background: #fff2f0;
          border-color: #f5222d;

          .stat-icon {
            background: #f5222d;
          }

          .stat-value {
            color: #f5222d;
          }
        }
      }
    }
  }

  .dialog-footer {
    text-align: right;
    padding-top: 16px;
    border-top: 1px solid #e9ecef;
  }
}
</style>
